package com.wyix;

import java.lang.reflect.Field;

/**
 * 操作字段
 *
 * @author wangdx
 * @since 2025/8/5
 */
public class FieldDemo {
    public static void main(String[] args) throws Exception {
        User user = new User();
        Class<?> userClass = user.getClass();

        // 获取私有字段
        Field nameField = userClass.getDeclaredField("name");
        nameField.setAccessible(true); // 允许访问私有字段

        // 设置字段值
        nameField.set(user, "Charlie");

        // 获取字段值
        String name = (String) nameField.get(user);
        System.out.println(name); // Charlie
    }
}